package com.example.administrator.androidwork5;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        String jsonStr = "  {\"temp\":\"20℃/30℃\",\"weather\":\"晴转多云\",\"name\":\"上海\",\"pm\":\"80\",\"wind\":\"1级\"},";
        String jsonArrayStr = "[\n" +
                "  {\"temp\":\"20℃/30℃\",\"weather\":\"晴转多云\",\"name\":\"上海\",\"pm\":\"80\",\"wind\":\"1级\"},\n" +
                "  {\"temp\":\"15℃/24℃\",\"weather\":\"晴\",\"name\":\"北京\",\"pm\":\"98\",\"wind\":\"3级\"},\n" +
                "  {\"temp\":\"26℃/32℃\",\"weather\":\"多云\",\"name\":\"广州\",\"pm\":\"30\",\"wind\":\"2级\"}\n" +
                "]";
       try {
           JSONObject jsonObject = new JSONObject(jsonStr);//将字符串转换为json对象
           String temp =jsonObject.getString("temp");//读取json对象中的属性值
           String weather = jsonObject.getString("weather1");

           Log.e(TAG, "onCreate: "+temp );
           //解析json数组字符串
           JSONArray jsonArray = new JSONArray(jsonArrayStr);
           Log.e(TAG, "onCreate: "+jsonArray.length() );
           for(int i =0;i<jsonArray.length();i++){
               JSONObject jsonObject1 = jsonArray.getJSONObject(i);//从json数组对象中获取JSONObject元素


               temp = jsonObject1.getString("temp");//读取json对象中的属性值
               weather = jsonObject1.getString("weather");
               Log.e(TAG, "onCreate: "+temp+"=="+weather );

           }
           
       } catch (JSONException e) {
           e.printStackTrace();
       }


    }
}
